package com.yc.thread;

//在A线程中通过一个变量想控制B线程的运行

/**
 * volatile作用：
 * 1.保证变量对所有线程可见性
 * 2.禁止指令重排
 * 3.不保证原子性
 */
public class Test18_volatile {
    public static void main(String[] args) {
        Task task =new Task();
        Thread thread1 =new Thread(task,"线程1");
        thread1.start();

        Thread thread2 =new Thread(()->{
            try {
                Thread.sleep(1000);
                System.out.println("开始通知");
                task.stop=true;
            } catch (InterruptedException e) {
                e.printStackTrace();

            }

        },"线程二");
        thread2.start();
        //Thread.sleep(1000);
    }
}
class Task implements  Runnable{
    //内存可见，每个线程有自己的工作空间通知主内存也改了
    boolean stop = false;//标量,用于标识当前线程运行的状态
    int i=0;
    @Override
    public void run() {
        long start =System.currentTimeMillis();
        while(!stop){
            i++;
        }
        System.out.println("线程退出,运行时间"+(System.currentTimeMillis()-start));
    }
}